<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use app\common\model\UserFinanceLog;
use fast\Tree;
use think\Db;
use think\Exception;

use think\exception\PDOException;
use think\exception\ValidateException;

use app\admin\model\User;
use app\admin\model\wanlshop\Shop;

/**
 * 链接管理
 *
 * @icon fa fa-circle-o
 */
class Invoice extends Backend
{

    /**
     * Link模型对象
     * @var \app\admin\model\wanlshop\Link
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Invoice;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $filter = json_decode($this->request->request('filter'), true);
            $filter = $filter ? $filter['type'] : false;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as $lk => $lv) {
                $list[$lk]['username'] = User::where("id", $lv['uid'])->value('nickname');
                $list[$lk]['shopname'] = Shop::where("id", $lv['shopid'])->value("shopname");
                switch ($lv['sh']) {
                    case '0':
                        $list[$lk]['status_text'] = "待审核";
                        break;
                    case '1':
                        $list[$lk]['status_text'] = "审核通过";
                        break;
                    case '2':
                        $list[$lk]['status_text'] = "审核驳回";
                        break;
                    case '3':
                        $list[$lk]['status_text'] = "已使用";
                        break;
                    default:
                        $list[$lk]['status_text'] = "审核中";
                        break;
                }
            }
            // 追加全局子页面
            if (!$filter || $filter == 'page') {
                $page = model('app\admin\model\wanlshop\Page')
                    ->where(['shop_id' => 0, 'type' => 'page'])
                    ->limit($offset, $limit)
                    ->select();
                $pageData = [];
                foreach ($page as $vo) {
                    $pageData[] = [
                        'id' => '70000' . $vo['id'],
                        'type' => 'page',
                        'title' => $vo['name'],
                        'route' => '/pages/page/index?id=' . $vo['page_token'],
                        'createtime' => $vo['createtime'],
                        'updatetime' => $vo['updatetime'],
                        'status' => 'normal',
                        'type_text' => '自定义页面',
                        'status_text' => '正常',
                        'weigh' => 1
                    ];
                }
                $list = array_merge($list, $pageData);
            }
            // 输出
            $result = array("total" => count($list), "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null, $except = false)
    {
        $row = $this->model->with(['user' => function ($query) {
            $query->withField('id,username');
        }, 'shop' => function ($query) {
            $query->withField('id,shopname');
        }])->find($ids);
        if (!$row) {
            $this->error(__('该数据为自动生成，不可修改'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($row->sh != 0) {
                    $this->success();
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    //增加用户发票余额
                    if ($params['sh'] == 1) {
                        $user = \app\common\model\User::find($row->uid);
                        UserFinanceLog::addRecord([[
                            'user_id' => $user->id,
                            'type' => 'invoice',
                            'flag' => 'add',
                            'value' => $row->price,
                            'before' => $user->invoice,
                            'after' => bcadd($user->invoice, $row->price, 2),
                            'event' => 'sys',
                            'rel_id' => $row->id,
                            'status' => 'succeed',
                        ]]);
                        $user->invoice = bcadd($user->invoice, $row->price, 2);
                        $user->save();
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}

